import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_app/widgets/Button/index.dart';

class RazorpayComp extends StatefulWidget {
  @override
  _RazorpayCompState createState() => _RazorpayCompState();
}

class _RazorpayCompState extends State<RazorpayComp> {
  static const platform = const MethodChannel("razorpay_flutter");

  Razorpay _razorpay;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 25, right: 25),
      child: Button(
        text: 'Repay',
        size: 'sm',
        onClick: openCheckout,
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _razorpay = Razorpay();
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
    _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
  }

  @override
  void dispose() {
    super.dispose();
    _razorpay.clear();
  }

  void openCheckout() async {
    // rzp_live_z7zuCI6Mt2rCYC
    // rzp_test_SI0DuugYfufLhs
    var options = {
      'key': 'rzp_test_SI0DuugYfufLhs',
      'amount': 8000 * 100,
      'image': 'https://app.atome.in/static/images/atome_logo.png',
      'name': 'Atome Credit',
      'description': 'Let\'s make',
      'prefill': {'contact': '9996792380', 'email': 'test@razorpay.com'},
      'external': {
        'wallets': ['paytm']
      }
    };

    try {
      _razorpay.open(options);
    } catch (e) {
      debugPrint(e);
    }
  }

  void _handlePaymentSuccess(PaymentSuccessResponse response) {
    Fluttertoast.showToast(
        gravity: ToastGravity.CENTER,
        msg: "SUCCESS: " + response.paymentId,
        timeInSecForIos: 4);
  }

  void _handlePaymentError(PaymentFailureResponse response) {
    Fluttertoast.showToast(
        gravity: ToastGravity.CENTER,
        msg: "ERROR: " + response.code.toString() + " - " + response.message,
        timeInSecForIos: 4);
  }

  void _handleExternalWallet(ExternalWalletResponse response) {
    Fluttertoast.showToast(
        gravity: ToastGravity.CENTER,
        msg: "EXTERNAL_WALLET: " + response.walletName,
        timeInSecForIos: 4);
  }
}
